<?php
namespace App\Model\Backstage;
use App\Model\Base;
use App\Model\Common\Module;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


/**
 * Class Department
 * @package App\Model\Backstage
 *公司对应部门model
 * date:2018-4-30
 * author :lxy
 */
class Department extends Base
{
    /**
     * @param array $map 查找的条件
     * @param string $order  排序方式
     */
    protected $table = 'department';

    //查看系统管理组的信息
    public function getSystemInfo()
    {
        return DB::table($this->table)
            ->leftJoin('user','charge','u_id')
            ->where('c_id', $this->branch_id)
            ->where('d_superior_id', 0)
            ->select('id','c_id','name','type','tel','address','u_username', 'charge','receivable',
                'received','to_work_time','after_work_time')
            ->get();
    }

    //获取系统管理组的ID
    public function getSystemId()
    {
        return $this->where('c_id', $this->branch_id)->where('d_superior_id', 0)->value('id');
    }
     /**
     * @param array $map
     * @return mixed
     * 获取部门列表  部门刚进去列表只展示 系统管理组 以及二级部门
     */
    public function getDepartmentList($pageLimit,$map = [], $d_superior_id)
    {
        if ($d_superior_id) {
            $superior_id = $d_superior_id;
        } else {
            $superior_id = DB::table($this->table)->where('c_id', $this->branch_id)->value('id');//该公司系统管理组的ID
        }
        $list = DB::table($this->table)
            ->leftJoin('user','charge','u_id')
            ->where('d_superior_id', $superior_id)
            ->where($this->table.'.is_del', 0)
            ->where($map)
            ->select('id','c_id','name','type','tel','address','u_username',
                'charge', 'receivable', 'received','to_work_time','after_work_time',
                DB::raw('from_unixtime(h_'.$this->table.'.updated_at) as updated_at'),
                DB::raw('from_unixtime(h_'.$this->table.'.created_at) as created_at'))
            ->orderBy('id','desc')
            ->paginate($pageLimit);
        if (sizeof($list) == 0){
            return false;
        }
        return $list;
    }

    /**
     * @param $params
     * @return mixed
     * 添加公司对应部门
     */
    public function addDepartment ($params)
    {
        $params['c_id'] = $this->branch_id;
        $params['created_at'] = time();
        $params['updated_at'] = time();
        $dId = $this->insertGetId($params);
        if($dId){
            $content = '添加部门：部门名称 => '.$params['name'];
            $log = new Log();
            $log->addlog($this->store_id,$this->uid,12,$content,$this->branch_id);
            return true;
        } else {
            return false;
        }


    }

    /**
     * @param $params
     * @return mixed
     * 修改部门信息
     */
    public function saveDepartment ($params)
    {
        $params['updated_at'] = time();
        $result =  $this->where(['id' => $params['id']])->update($params);
        if($result){
            $oldInfo = DB::table('department')->where('id',$params['id'])->select('name','type','tel','charge')->first();
            $content = '修改部门：';
            if($oldInfo->name != $params['name']){
                $content .= ' 部门名称： '.$oldInfo->name.' => '.$params['name'];
            }
            if($oldInfo->type != $params['type']){
                $content .= ' 部门类型： '.$oldInfo->type.' => '.$params['type'];
            }
            if($oldInfo->tel != $params['tel']){
                $content .= ' 部门电话： '.$oldInfo->tel.' => '.$params['tel'];
            }
            if($oldInfo->charge != $params['charge']){
                $content .= ' 部门负责人： '.$oldInfo->charge.' => '.$params['charge'];
            }
            if($content != '修改部门：'){
                $log = new Log();
                $log->addlog($this->store_id,$this->uid,12,$content);
            }

        }
        return $result;
    }

    /**
     * 根据部门ID 修改部门的权限
     */
    public static function editDepartmentPermission($params)
    {
        $d_authories = explode(',', $params['d_authories']);
        $arr = DB::table('nosplit_authority as na')
            ->leftJoin('nosplit_module as nm', 'na.module_id', '=', 'nm.id')
            ->whereIn('na.id', $d_authories)
            ->select(DB::raw('GROUP_CONCAT(h_nm.nm_type) as nm_type'), DB::raw('GROUP_CONCAT(h_na.module_id) as module_id'), DB::raw('GROUP_CONCAT(h_na.id) as id'))
            ->get();
        $type = explode(',', $arr[0]->nm_type);//模块类型
        $module_id = explode(',', $arr[0]->module_id);//模块ID
        $id = explode(',', $arr[0]->id);//权限ID
        $authories = '';
        foreach ($type as $k=>$v) {
            $authories .= $v.'|'.$module_id[$k].'|'.$id[$k].',';
        }
        return DB::table('department')->where('id', $params['id'])->update(['d_authories' => $authories, 'updated_at' => time()]);
    }
    /**
     * 修改了部门权限以后   在批量修改该部门下面所有员工的权限
     */
    public static function editDepartmentDownUserPermission($id)
    {
        $d_authories = DB::table('department')->where('id', $id)->value('d_authories');
        //部门下面所有员工的ID
        $userIdArr = DB::table('user')->where('u_d_id', $id)->value(DB::raw('GROUP_CONCAT(u_id) as u_id'));
        if (!$userIdArr) {
            return -1;
        }
        $userIdArr = explode(',', $userIdArr);
        return DB::table('user')->whereIn('u_id', $userIdArr)->update(['authories' => $d_authories, 'updated_at' => time()]);
    }


    /**
     * @param $user
     * @param $d_id
     * @return array
     * 软删除部门与恢复 判断部门下面是否有用户
     */
    public function delDepartment($d_id)
    {
        $department = DB::table('department')->where('d_superior_id', $d_id)->where('is_del', 0)->value('id');  //查找是否有下级部门
        if ($department) {
            return ['code' => 1, 'msg' => '此部门下面存在下级部门，不能删除！'];
        }
        $list = DB::table('user')->where('u_d_id', $d_id)->where('is_del', 0)->value('u_id');  //查找是否有用户
        if($list){
            return ['code' => 1, 'msg' => '此部门下面存在用户，不能删除！'];
        }
        $oldStatus = DB::table('department')->where('id',$d_id)->value('is_del');
        $oldname = DB::table('department')->where('id',$d_id)->value('name');
        $log = new Log();
        if($oldStatus == 0){
            //删除操作
            $res = $this->where(['id'=>$d_id])->update(['is_del' => 1, 'updated_at' => time(),
                'd_del_user'=>$this->uid,'d_del_department'=>$this->store_id]);
            if($res){
                $content = '删除部门：部门名称 => '.$oldname;
                $log->addlog($this->store_id,$this->uid,12,$content);
            }
        }elseif($oldStatus == 1){
            //恢复操作
            $res = $this->where(['id'=>$d_id])->update(['is_del' => 0, 'updated_at' => time()]);
            if($res){
                $content = '恢复部门：部门名称 => '.$oldname;
                $log->addlog($this->store_id,$this->uid,12,$content);
            }
        }else{
            return -1;
        }
        if($res){
                return ['code' => 0, 'msg' => '删除成功'];
            }else{
                return ['code' => 1, 'msg' => '删除失败'];
            }
    }

    /**回收站  彻底删除（改变状态） 部门
     * @param $id
     * @return bool
     */
    public function recycleDelDepartment($id)
    {
        $data = DB::table('department')->where('id', $id)->select('name', 'is_del')->first();
        if ($data->is_del == 1) {
            $res =  DB::table('department')->where('id', $id)->where('is_del', 1)->update([
                'is_del'           =>  2,
                'd_del_user'       =>  $this->uid,
                'd_del_department' =>  $this->store_id
            ]);
            if ($res) {
                $log = new Log();
                $content = '回收站删除部门：部门名称 => '.$data->name;
                $log->addlog($this->store_id,$this->uid,12,$content);
                return $res;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**获取中介公司下面的部门列表
     * @param array $map
     * @return mixed
     */
    public function getAllDropdown()
    {
        $allDev = $this->where('c_id', $this->branch_id)
            ->where('is_del', 0)
            ->select('id as value', 'name as label')
            ->get();
        if (sizeof($allDev) == 0){
            return false;
        }
        return[
            [
            "label" => '所有部门',
            "options" => $allDev->toArray()
        ]];

    }
    // 跨部的所有部门
    public function getInterPartDropdown()
    {
        $systemId = $this->where('c_id', $this->branch_id)->value('id');//该公司系统管理组的ID
        $secondary = $this->where('c_id', $this->branch_id)
            ->where('d_superior_id', $systemId)
            ->where('is_del', 0)
            ->select('id as value', 'name as label')
            ->get();
        if (sizeof($secondary) == 0){
            return false;
        }
        foreach ($secondary as $k=>$v) {
            $v['options'] = $this->where('d_superior_id', $v['value'])->orWhere('id', $v['value'])->select('id as value', 'name as label')->get();
        }
        return $secondary;
    }
    //  本部  本人
    public function getHeadquartersDropdown()
    {
        $secondary = $this->where('id', $this->store_id)
            ->where('is_del', 0)
            ->select('id as value', 'name as label')
            ->get();
        if (empty($secondary)){
            return false;
        }
        return [
            [
            "label" => $secondary[0]['label'],
            "options" => $secondary->toArray()
        ]];
    }


    /**
     * 获取部门下面员工的列表
     */
    public  function downList($where)
    {
        return DB::table('user')->where('u_b_id', $this->branch_id)->where('is_del', 0)->where($where)->select('u_id', 'u_username')->get();
    }
    /**
     * 根据部门ID 获取该部门的名字
     */
    public static function getDeparName($id)
    {
        return DB::table('department')->where('id', $id)->value('name');
    }
    /**
     * 部门回收站列表
     * 部门Id 部门名称 部门类型 部门电话 部门地址 部门负责人 删除人 删除人部门 删除时间
     */
    public function recycleBinList($pageLimit,$where,$keywords){
        if($keywords == ''){
           $list =  DB::table('department')
                ->leftjoin('user','u_id','charge')
                ->where('department.is_del',1)
                ->where($where)
                ->select('id','name','type','tel','address','u_username','d_del_user','d_del_department',DB::raw('from_unixtime(h_department.updated_at) as updated_at'))
                ->orderBy('department.updated_at', 'desc')
                ->paginate($pageLimit);
        }else{
            $list =  DB::table('department')
                ->leftjoin('user','u_id','charge')
                ->where('department.is_del',1)
                ->where($where)
                ->where(function ($query) use($where, $keywords){
                    $query->where($where)->where('name', 'like', '%'.$keywords.'%');//部门名称
                })->orWhere(function ($query) use($where, $keywords) {
                    $query->where($where)->where('tel', 'like', '%'.$keywords.'%');//部门电话
                })
                ->select('id','name','type','tel','address','u_username','d_del_user','d_del_department',DB::raw('from_unixtime(h_department.updated_at) as updated_at'))
                ->orderBy('department.updated_at', 'desc')
                ->paginate($pageLimit);
        }
        if(sizeof($list) == 0){
            return false;
        }
        foreach($list as $key=>$value){

            $delUserInfo = DB::table('user')
                        ->leftjoin('department','id','c_id')
                        ->where('u_id',$value->d_del_user)
                        ->select('u_username','name')
                        ->first();
            if($delUserInfo){
                $value->d_del_user = $delUserInfo->u_username;
                $value->d_del_department = $delUserInfo->name;
            }else{
                $value->d_del_user = '';
                $value->d_del_department = '';
            }

        }
        return $list;
    }

}